package volkov.ja.pages;

import static org.openqa.selenium.support.ui.ExpectedConditions.*;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.Select;

public class MovieListPage extends InternalPage {

	public MovieListPage(PageManager pages) {
		super(pages);
	}

	@FindBy(id = "results")
	private WebElement results;

	@FindBy(id = "q")
	private WebElement searchField;

	@FindBy(css = "nav a[href $= '?go=add']")
	private WebElement addMovieLink;

	private static By pageReadyBy = By.cssSelector("div#results");

	// private Select permissionDropdown() {
	// return new Select(driver.findElement(By.name("permission")));
	// }
	// public String getRole() {
	// return permissionDropdown().getFirstSelectedOption().getText();
	// }

	public String getSearchField() {
		return searchField.getAttribute("value");
	}

	public MovieListPage setSearchField(String text) {
		searchField.sendKeys(text);
		return this;
	}

	@Override
	public String getPageRelativeUrl() {
		return "";
	}

	public MovieCreatePage clickAddMovieLink() {
		addMovieLink.click();
		return pages.movieCreatePage;
	}

	@Override
	public MovieListPage ensurePageLoaded() {
		super.ensurePageLoaded();
		pages.getWait().until(presenceOfElementLocated(pageReadyBy));
		return this;
	}

	@Override
	public boolean pageReady() {
		try {
			pages.getWebDriver().findElement(pageReadyBy);
		} catch (NoSuchElementException e) {
			return false;
		}
		return true;
	}

	public ArrayList<String> getMovieIds(String title, boolean partialSearch) {
		ArrayList<String> out = new ArrayList<String>();
		List<WebElement> wes = pages.getPageUtils().getElementsHavingChildWithContent(
				By.className("movie_box"), By.className("title"), title,
				partialSearch);
		for (WebElement we : wes) {
			out.add(we.getAttribute("id"));
		}
		return out;
	}

	public ArrayList<String> getMovieIds(String title) {
		return getMovieIds(title, false);
	}

	public void clickMovieViewLink(String id) {
		pages.getPageUtils().clickIfPresent(By.id(id));
	}

}
